package cn.mw.cmdb.view;

import cn.mw.cmdb.entity.ModelInfo;
import cn.mw.microMonitorCommon.api.user.MwUserApi;
import cn.mw.microMonitorCommon.security.dto.MwUser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ModelTableConverter implements ViewConvert<ModelInfo ,ModelTableView>{
    @Override
    public ModelTableView convert(ModelInfo param ,ViewConvertContext context) {
        ModelTableView view = new ModelTableView();
        view.extractFromModelInfo(param);
        return view;
    }

    @Override
    public void finish(ViewConvertContext context, List<ModelTableView> list) throws Exception {
        MwUserApi mwUserApi = (MwUserApi)context.get(ViewConvertContext.MwuserApiKey);
        if(null != mwUserApi){
            List<Long> userIds = new ArrayList<>();
            if(null != list){
                for(ModelTableView view : list){
                    userIds.add(view.getCreater());
                }

                if(userIds.size() > 0){
                    List<MwUser> users = mwUserApi.getUsersByUserIds(userIds);
                    if(null != users && users.size() > 0){
                        Map<Long ,String> userNameMap = new HashMap<>();
                        for(MwUser mwUser : users){
                            userNameMap.put(mwUser.getId(), mwUser.getUsername());
                        }

                        for(ModelTableView view : list){
                            view.setCreaterName(userNameMap.get(view.getCreater()));
                        }
                    }
                }
            }
        }
    }
}
